home *** CD-ROM | disk | FTP | other *** search
/ Language/OS - Multiplatform Resource Library / LANGUAGE OS.iso / lisp / wgdb-42.lha / wgdb-4.2 / libiberty / strtoul.c < prev   
C/C++ Source or Header  |  1992-09-11  |  2KB  |  91 lines

  1. /*
  2.  * strtol : convert a string to long.
  3.  *
  4.  * Andy Wilson, 2-Oct-89.
  5.  */
  6.  
  7. #include <errno.h>
  8. #include <ctype.h>
  9. #include <stdio.h>
  10. #include "ansidecl.h"
  11.  
  12. #define    ULONG_MAX    0xFFFFFFFF
  13.  
  14. extern int errno;
  15.  
  16. unsigned long
  17. strtoul(s, ptr, base)
  18.      CONST char *s; char **ptr; int base;
  19. {
  20.   unsigned long total = 0, tmp = 0;
  21.   unsigned digit;
  22.   int radix;
  23.   CONST char *start=s;
  24.   int did_conversion=0;
  25.  
  26.   if (s==NULL)
  27.     {
  28.       errno = ERANGE;
  29.       if (!ptr)
  30.     *ptr = (char *)start;
  31.       return 0L;
  32.     }
  33.  
  34.   while (isspace(*s))
  35.     s++;
  36.   if (*s == '+')
  37.     s++;
  38.   radix = base;
  39.   if (base==0 || base==16)
  40.     {
  41.       /*
  42.        * try to infer radix from the string
  43.        * (assume decimal).
  44.        */
  45.       if (*s=='0')
  46.     {
  47.       radix = 8;    /* guess it's octal */
  48.       s++;        /* (but check for hex) */
  49.       if (*s=='X' || *s=='x')
  50.         {
  51.           s++;
  52.           radix = 16;
  53.         }
  54.     }
  55.     }
  56.   if (radix==0)
  57.     radix = 10;
  58.  
  59.   while ( digit = *s )
  60.     {
  61.       if (digit >= '0' && digit < ('0'+radix))
  62.     digit -= '0';
  63.       else
  64.     if (radix > 10)
  65.       {
  66.         if (digit >= 'a' && digit < ('a'+radix))
  67.           digit = digit - 'a' + 10;
  68.         else if (digit >= 'A' && digit < ('A'+radix))
  69.           digit = digit - 'A' + 10;
  70.         else
  71.           break;
  72.       }
  73.     else
  74.       break;
  75.       did_conversion = 1;
  76.       tmp = (total * radix) + digit;
  77.       if (tmp < total)    /* check overflow */
  78.     {
  79.       errno = ERANGE;
  80.       if (ptr != NULL)
  81.         *ptr = (char *)s;
  82.       return (ULONG_MAX);
  83.     }
  84.       total = tmp;
  85.       s++;
  86.     }
  87.   if (ptr != NULL)
  88.     *ptr = (char *) ((did_conversion) ? (char *)s : start);
  89.   return (total);
  90. }
  91.